﻿using Infrastructure.Log;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Security.Des
{
    /// <summary>
    /// des加密
    /// </summary>
    public class DesHelper
    {
        /// <summary>
        /// Key值
        /// </summary>
        public static string Key { get; set; } = "3n2G7Mpb";//24位

        /// <summary>
        /// IV值
        /// </summary>
        public static string IV { get; set; } = "W0I9suLJ";//8位

        #region ========加密========
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="text">待加密文本</param>
        /// <returns></returns>
        public static string Encrypt(string text)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            var inputByteArray = Encoding.UTF8.GetBytes(text);
            des.Key = Encoding.UTF8.GetBytes(Key);
            des.IV = Encoding.UTF8.GetBytes(IV);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }

        #endregion

        #region ========解密========
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="text">待解密文本</param>
        /// <returns></returns>
        public static string Decrypt(string text)
        {

            var len = text.Length / 2;
            byte[] inputByteArray = new byte[len];
            int x, i;
            for (x = 0; x < len; x++)
            {
                i = Convert.ToInt32(text.Substring(x * 2, 2), 16);
                inputByteArray[x] = (byte)i;
            }
            DESCryptoServiceProvider des = new DESCryptoServiceProvider()
            {
                Key = Encoding.UTF8.GetBytes(Key),
                IV = Encoding.UTF8.GetBytes(IV)
            };

            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {

                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Encoding.UTF8.GetString(ms.ToArray());

            }
        }
        #endregion
    }
}
